package com.zbkj.crmeb.order.channel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.utils.PriceUtil;
import com.utils.RestTemplateUtil;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.request.BellettiniOrderRequest;
import com.zbkj.crmeb.order.response.ImOrderResponse;
import com.zbkj.crmeb.plat.by.dto.Result;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.service.CommonStoreOrderService;
import com.zbkj.crmeb.store.service.StoreOrderInfoService;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 易镭订单推送
 * @author chenchongli
 * @date:  2024-04-15 11:49
 */
@Service("easyStoreOrderServiceImpl")
@Slf4j
public class EasyStoreOrderServiceImpl extends AbstractStoreOrderService implements ApplicationRunner {

    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    StoreOrderFactory storeOrderFactory;

    @Resource
    private StoreOrderDao storeOrderDao;

    private final static String APIURL = "http://api.hiqlty.com/pub/order";
    private final static String APPKEY = "9UMF47WBSH9U5MMQU0W95N9L7GYR32VL"; //密钥
    private final static String PARTNERID = "58069385";

    @Resource
    private StoreOrderService storeOrderService;
    @Resource
    private StoreOrderInfoService storeOrderInfoService;
    @Override
    public void run(ApplicationArguments args) throws Exception {
//        doTest();
    }
    public void doTest(){
        DingTalkMsgUtil.sendMsg(DingMsgEnum.OTHER,"推送易磊测试单");
        StoreOrder storeOrder = storeOrderService.getByOrderId("FD2024052217593323519");
        List<StoreOrderInfoVo> orderListByOrderId = storeOrderInfoService.getOrderListByOrderId(storeOrder.getId());
        Result result = pushOrder(storeOrder, orderListByOrderId);
        System.out.println();
        DingTalkMsgUtil.sendMsg(DingMsgEnum.OTHER,"推送易磊返回"+JSON.toJSONString(result));

    }

    @Override
    public CommonResult<Object> addChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        Result result;
        try {
            result = pushOrder(storeOrder, orderInfoVoList);
        } catch (Exception e) {
            result = Result.getFailureResult("system error","系统异常");
            log.error("推送易磊订单异常: " , e);
        }
        if (!result.isSuccess()) {
            return CommonResult.failed(result.getMessage());
        }
        return CommonResult.success();
    }

    /**
     * 订单推送
     * @param storeOrder
     * @param order
     * @return
     */
    public Result pushOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfos) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 构建请求参数
        JSONObject requestData = new JSONObject();
        requestData.put("partnerid", PARTNERID);

        // 业务信息
        requestData.put("orderNo", storeOrder.getOrderId());
        requestData.put("createTime", sdf.format(storeOrder.getCreateTime()));
        requestData.put("ShopName", "海客来");
        requestData.put("payAmount", storeOrder.getPayPrice());
        String payCompany = getPayCompany(storeOrder.getPayType());
        if (StringUtils.isBlank(payCompany)){
            return Result.getFailureResult("payCompany is error","支付方式未匹配,请检查");
        }
        requestData.put("payCompanyName", payCompany);
        // 处理别样支付单号
        requestData.put("PayOrderNo", storeOrder.getOrderId().contains("BY") ? storeOrder.getPayNo() : storeOrder.getOutOrderId());
        requestData.put("payTime", sdf.format(storeOrder.getPayTime()));
        requestData.put("PurcName", storeOrder.getRealName());
        requestData.put("PurcPaperNumber", storeOrder.getIdCard());
        requestData.put("consignee", storeOrder.getCreateName());
        if (storeOrder.getCreateTime().compareTo(storeOrder.getPayTime()) > 0) {
            return Result.getFailureResult("time is error","创建时间大于支付时间,请检查");
        }

        String phoneNumber = storeOrder.getUserPhone();
        String phone = getPhone(phoneNumber);
        if (StringUtils.isBlank(phone)){
            return Result.getFailureResult("phone is error","电话号码不符合,请检查");
        }
        requestData.put("consigneeTel", phone);
        requestData.put("Province", storeOrder.getProvince());
        requestData.put("city", storeOrder.getCity());
        requestData.put("area", storeOrder.getDistrict());
        requestData.put("address", storeOrder.getDetail());
        requestData.put("orderType", 0);
        requestData.put("note", storeOrder.getMark());
        // 商品信息
        JSONArray orderItems = new JSONArray();
        BigDecimal totalGoodsPrice = BigDecimal.ZERO;
        for (StoreOrderInfoVo orderInfo : orderInfos) {
            JSONObject goods = new JSONObject();
            goods.put("itemNo", orderInfo.getInfo().getProductInfo().getKeyword());
            goods.put("itemQuantity", orderInfo.getInfo().getCartNum());
            goods.put("itemPrice", orderInfo.getPayPrice());
            totalGoodsPrice = totalGoodsPrice.add(orderInfo.getPayPrice());
            orderItems.add(goods);
        }
        if (totalGoodsPrice.compareTo(storeOrder.getPayPrice()) != 0) {
            return Result.getFailureResult("price is error","商品总价不等于支付金额,请检查");
        }
        requestData.put("orderItems", orderItems);
        log.info("<<--------易镭推单数据: {}--------->>", requestData);

        // 将requestData转换为JSON字符串
        String result = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            String jsonRequestData = new ObjectMapper().writeValueAsString(requestData);
            // 计算签名
            String content = APPKEY + jsonRequestData + APPKEY;
            String sign = DigestUtils.md5Hex(content).toUpperCase();
            // 请求头
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("sign", sign);

            // 创建HttpEntity对象，包含请求头和请求体
            HttpEntity<String> requests = new HttpEntity<>(jsonRequestData, headers);
            // 发送请求
            result = new RestTemplate().postForEntity(APIURL + "/receive", requests, String.class).getBody();
            log.info("--------------- 易镭订单推送接口返回, result: {} ---------------", result);
            DingTalkMsgUtil.sendMsg(DingMsgEnum.OTHER,"推送易磊返回"+result);
        }  catch (HttpClientErrorException | HttpServerErrorException e) {
            log.error("API请求失败, 状态码: {}", e.getStatusCode());
            log.error("错误报文: {}" , e.getResponseBodyAsString());
        } catch (Exception e) {
            log.error("发生其他异常错误: " , e);
        }

        JSONObject resultObj = JSON.parseObject(result);
        // 获取状态
        boolean isSuccess = resultObj.getBoolean("success");
        // 反馈的信息
        String message = resultObj.getString("message");
        // 修改订单状态
        StoreOrder storeOrderUpdate = new StoreOrder();
        storeOrderUpdate.setId(storeOrder.getId());
        if(isSuccess) {
            //新增采购单
            storeOrderFactory.insertPurchaseOrder(storeOrder, isSuccess, PurchaseOrderChannelTypeEnum.CROSSEASY.getCode());
            //新增采购商品
            for (StoreOrderInfoVo orderInfo : orderInfos) {
                storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, isSuccess, message, null);
            }
            storeOrderUpdate.setPushStatus(1);
            storeOrderUpdate.setPushMessage("Easy推送: 成功");
            storeOrderDao.updateById(storeOrderUpdate);
            log.info("--------------- 易镭订单推送成功, orderNo: {} ---------------", storeOrder.getOrderId());
            return new Result(true, null, message);
        } else {
            storeOrderUpdate.setPushStatus(2);
            storeOrderUpdate.setPushMessage("Easy推送:失败, " + message);
            storeOrderDao.updateById(storeOrderUpdate);
            log.error("--------------- 易镭订单推送接口异常, message: {} ---------------", message);
            return new Result(false, null, message);
        }
    }

    private String getPayCompany(String payType) {
        String company = "";
        if("weixin".equalsIgnoreCase(payType) || "WECHAT".equalsIgnoreCase(payType)){
            company = "微信";
        }else if("alipay".equalsIgnoreCase(payType)){
            company = "支付宝";
        }else if("adapay_degree".equalsIgnoreCase(payType)){
            company = "汇付";
        }
        return company;
    }

    private static String getPhone(String phoneNumber) {
        if (StringUtils.isBlank(phoneNumber)){
            return "";
        }
        String[] split = phoneNumber.split(" ");
        if (split.length<1){
            return "";
        }
        String tmpPhone = "";
        if (split.length == 1){
            tmpPhone = split[0];
        }
        if (split.length == 2){
            tmpPhone = split[1];
        }
        if (tmpPhone.length()<11){
            return "";
        }
        return tmpPhone;
    }

    @Override
    public CommonResult<Object> cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        return null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        return null;
    }
}
